package com.dhj.utils;

import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @author DaHuaJia
 * @Description HttpUtils 类
 * @Date 2021-11-20 13:27:03
 */
@Component
public class HttpUtils {

    /**
     * 连接池管理器
     */
    private PoolingHttpClientConnectionManager poolManager;

    public HttpUtils() {
        this.poolManager = new PoolingHttpClientConnectionManager();
        // 设置最大连接数
        this.poolManager.setMaxTotal(100);
        // 设置每个主机的最大连接数
        this.poolManager.setDefaultMaxPerRoute(10);
    }

    /**
     * 根据请求地址下载html页面数据
     *
     * @param url
     * @return html页面
     */
    public String doGetHtml(String url) {
        // 获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.poolManager).build();
        // 创建httpGet请求对象，设置url地址
        HttpGet httpGet = new HttpGet(url);

        httpGet.setHeaders(getHeaderArr());

        httpGet.setConfig(this.getConfig());

        CloseableHttpResponse response = null;
        try {
            // 使用HttpClient发起请求，获取响应
            response = httpClient.execute(httpGet);
            // 解析响应，返回结果
            if (response.getStatusLine().getStatusCode() == 200) {
                // 判断响应体Entity是否不为空
                if (response.getEntity() != null) {
                    String content = EntityUtils.toString(response.getEntity(), "utf8");
                    return content;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }


    /**
     * 根据请求地址下载图片
     *
     * @param url
     * @return 图片名称
     */
    public String doGetImages(String url) {
        // 获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.poolManager).build();
        // 创建httpGet请求对象，设置url地址
        HttpGet httpGet = new HttpGet(url);

        httpGet.setHeaders(getHeaderArr());

        httpGet.setConfig(this.getConfig());

        CloseableHttpResponse response = null;

        try {
            // 使用HttpClient发起请求，获取响应
            response = httpClient.execute(httpGet);
            // 解析响应，返回结果
            if (response.getStatusLine().getStatusCode() == 200) {
                // 判断响应体Entity是否不为空
                if (response.getEntity() != null) {
                    // 获取图片后缀
                    String extName = url.substring(url.lastIndexOf("."));
                    // 创建图片名，重命名图片
                    String picName = UUID.randomUUID().toString() + extName;

                    // 声明OutputStream
                    OutputStream outputStream = new FileOutputStream("D:\\Test\\Images\\" + picName);
                    // 下载图片
                    response.getEntity().writeTo(outputStream);

                    return picName;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return "";
    }


    /**
     * 设置请求信息
     *
     * @return
     */
    private RequestConfig getConfig() {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(6000)              // 创建连接最长时间
                .setConnectionRequestTimeout(3000)     // 获取连接的最长时间
                .setSocketTimeout(10000)              // 数据传输的最长时间
                .build();
        return config;
    }

    /**
     * 设置请求头
     *
     * @return
     */
    private Header[] getHeaderArr() {
        Header[] headers = new Header[12];
        headers[0] = new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0");
        headers[1] = new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8");
        headers[2] = new BasicHeader("Accept-Encoding", "gzip, deflate, br");
        headers[3] = new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        headers[4] = new BasicHeader("Connection", "keep-alive");
        headers[5] = new BasicHeader("Cookie", "ipLoc-djd=1-72-2799-0-"+UUID.randomUUID().toString());
        headers[6] = new BasicHeader("Host", "search.jd.com");
        headers[7] = new BasicHeader("Sec-Fetch-Dest", "document");
        headers[8] = new BasicHeader("Sec-Fetch-Mode", "navigate");
        headers[9] = new BasicHeader("Sec-Fetch-Site", "none");
        headers[10] = new BasicHeader("Sec-Fetch-User", "?1");
        headers[11] = new BasicHeader("Upgrade-Insecure-Requests", "1");
        return headers;
    }

}
